package com.zhangfb95.crosschain.console.command;

import com.zhangfb95.crosschain.console.enums.CommandEnum;
import com.zhangfb95.crosschain.infra.model.Result;
import com.zhangfb95.crosschain.infra.util.json.JsonUtil;
import com.zhangfb95.crosschain.sdk.CrossChainClient;
import com.zhangfb95.crosschain.sdk.infra.model.api.response.server.rpcchain.RpcGetBlockByNumberApiRes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author zhangfubing
 * @since 2024/1/2
 */
@Component
public class BlockInfoCommand implements Command {

    @Autowired
    private CrossChainClient crossChainClient;
    @Autowired
    private JsonUtil jsonUtil;

    @Override
    public CommandEnum command() {
        return CommandEnum.BLOCK_INFO;
    }

    @Override
    public boolean handle(String[] args) {
        if (args.length < 2 || isHelp(args)) {
            printHelpInfo();
            return false;
        }

        String chainPath = args[0];
        String blockNumberStr = args[1];

        long blockNumber;
        try {
            blockNumber = Long.parseLong(blockNumberStr);
        } catch (NumberFormatException e) {
            System.out.println("Result: please input right blockNumber");
            return false;
        }

        Result<RpcGetBlockByNumberApiRes> apiRes = crossChainClient.getBlockByNumber(chainPath, blockNumber);
        if (apiRes.isSuccess()) {
            apiRes.getData().setBlockBytes(null);
            System.out.println("Result: success");
            System.out.println("data: " + jsonUtil.toJsonQuietly(apiRes.getData()));
        } else {
            System.out.println("Result: " + apiRes.getMsg());
        }
        return false;
    }

    private void printHelpInfo() {
        System.out.println("Usage: blockInfo [chainPath] [blockNumber]");
    }
}
